﻿using Common;

using Frontdatabase;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Model;
using Model.UserModel;
using System.Security.Claims;
using System.Security.Cryptography;

namespace WebFront.Service.Impl
{

    public class UserSeviceImpl(
         FrontDbContext _frontDbContext, JwtHelper _jwtHelper
        ) : IUserSevice
    {
        /// <summary>
        /// 用户登录业务实现
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<ResResult> Login(UserLoginModel _usermodel)
        {
           var md5password= MD5Helper.ToMd5Str(_usermodel.Password, null);
          var user= _usermodel.Email is not null ? await _frontDbContext.Users
                                               
                                             .FirstOrDefaultAsync(u =>u.Email==_usermodel.Email && u.Password == md5password)
                                       : _usermodel.Phone is not null 
                                                            ? await _frontDbContext.Users
                                                              
                                                                .FirstOrDefaultAsync(u=>u.Phone== _usermodel.Phone && u.Password==md5password)
                                                            : null;

           if(user is null) 
            { return new ResResult(null!,ResultEnum.Error,"用户不存在"); }
           
            var claims = new Claim[]
              {
               new( nameof(user.Id), user.Id.ToString() ),
               new(nameof(user.Grade),user.Grade.ToString()),
           
              };
            //生成jwt
           var token= _jwtHelper.CreateToken( claims );

          
            return new ResResult(new
            {
               
               token= JwtBearerDefaults.AuthenticationScheme +" "+ token,
               
                user.Profile,
               loginTime= DateTime.Now,
            });
        }
    }
}
